package com.chen.demo.javase.algorithm.leetcode.editor.cn;
//反转一个单链表。 
//
// 示例: 
//
// 输入: 1->2->3->4->5->NULL
//输出: 5->4->3->2->1->NULL 
//
// 进阶: 
//你可以迭代或递归地反转链表。你能否用两种方法解决这道题？ 
// Related Topics 链表 
// 👍 1430 👎 0

import java.io.IOException;
import java.util.Scanner;

public class ReverseLinkedList {
    public static void main(String[] args) throws IOException {
        ListNode head = initList();
        ListNode node = solution(head);
        printList(node);
        System.out.println("end");
    }

//leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode initList() {
        System.out.println("链表长度:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        int length = Integer.parseInt(s);
        ListNode head = null;
        ListNode temp = null;
        System.out.println("以此输入链表数据:");
        while (length > 0) {
            if (head == null) {
                temp = new ListNode(Integer.parseInt(scanner.next()));
                head = temp;
            } else {
                temp.next = new ListNode(Integer.parseInt(scanner.next()));
                temp = temp.next;
            }

            length--;
        }
        return head;
    }

    public static void printList(ListNode head) {
        ListNode temp = head;
        while (temp != null) {
            System.out.print("" + temp.val + " ");
            temp = temp.next;
        }
        System.out.println("");
    }

    public static ListNode solution(ListNode head) {
        if (head.next == null) {
            return head;
        }
        ListNode temp;
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            // temp 暂存一个节点
            temp = cur.next;
            // 修改当前节点next为
            cur.next = pre;
            // 修改pre值，下一个节点的next就是当前节点
            pre = cur;
            // 修改cur值
            cur = temp;

        }
        return pre;
    }

    class Solution {
        public ListNode reverseList(ListNode head) {
            return null;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}